//
//  HMNetworkTools.swift
//  3.Swift中网络的封装
//
//  Created by heima on 16/4/8.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit
import AFNetworking

//swift 中的枚举
enum HMHttpMethods: String {
    case POST = "POST"
    case GET = "GET"
}

//使用结构体来定义API
struct API  {
   //线上环境
   static let onlineHost = "https://api.weibo.com/"
   
   //测试环境   在上次AppStore之前 一定要取消使用这个环境
    static let devHost = "https://dev.api.weibo.com/"
    
    static let authrizon = "oauth2/access_token"
    static let access_token = "2/users/show.json"
    
    static let homepage = "2/statuses/home_timeline.json"
}

class HMNetworkTools: AFHTTPSessionManager {
    //声明单例对象
    static let sharedTools: HMNetworkTools = {
        let tools = HMNetworkTools(baseURL: NSURL(string: API.onlineHost))
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    
   
}


//登录请求
extension HMNetworkTools {

    func loadAccessToken(code: String,finished: (result: AnyObject?,error: NSError?) -> ()) {
    
    
    //AFN中参数 以字典的形式传递
    let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type": "authorization_code","code":code,"redirect_uri":redirect_uri]
     //调用核心方法
      request(.POST, urlString: API.authrizon, parameters: parameters, finished: finished)
    }
    
    //MARK:加载用户的信息
    
    func loadUserInfo(token: AnyObject, uid: AnyObject,finished: (result: AnyObject?, error: NSError?) -> ()) {
        
        //字典数组中不能够添加nil
        let parameters = ["access_token": token, "uid": uid]
        request(.GET, urlString: API.access_token, parameters: parameters, finished: finished)
    }

}


//MARK:首页数据相关
extension HMNetworkTools {

    func loadHomePageData(token: String,finished: (result: AnyObject?, error: NSError?) -> ()){
    
        let parameters = ["access_token" : token]
        
        request(.GET, urlString: API.homepage, parameters: parameters, finished: finished)
    }

}


//网络请求
extension HMNetworkTools {

    //封装所有的网络请求方法 所有的网络请求都是通过这个方法和 AFN进行联系
    func request(method: HMHttpMethods,urlString: String, parameters: AnyObject?, finished: (result: AnyObject?, error: NSError?) -> ()) {
        
        //swift中就不能够使用利用协议 欺骗Xcode
        //为了达到封装的目的 可以将相同的闭包 抽取出来,当做参数传递给AFN框架
        let success =  { (task: NSURLSessionDataTask, result: AnyObject?) -> Void in
            //执行成功的回调
            finished(result: result, error: nil)
        }
        
        //定义失败的回调
        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
            //执行失败的回调
            
            print(error)
            finished(result: nil, error: error)
        }
        
        if method == .GET {
            GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }

    
}
